#!/bin/bash

DEV_TRACE=${DEV_TRACE:+true}
DEV_DEBUG=${DEV_DEBUG:+true}
DEV_TRACE=${DEV_TRACE:-false}
DEV_DEBUG=${DEV_DEBUG:-${DEV_TRACE}}

case ${DEV_DEBUG} in
  true)
    DEV_CLEAN=false
    ;;
  false)
    DEV_CLEAN=true
    ;;
esac

$DEV_TRACE && set -x

DEV_HOME=${DEV_HOME:-/opt/devel}
_DEV_BASE=.dev
_DEV_CONF=${_DEV_BASE}/conf
_DEV_TOOLS=${_DEV_BASE}/tools
_DEV_TOOLS_DIR=${DEV_HOME}/tools

include () {
	local file
	file=${1:?missing file}

	if [ ! -d ${file%/*} ]; then
		$DEV_DEBUG && echo "${file%/*} does not exist" 1>&2
		return
	elif [ ! -f ${file} ]; then
		$DEV_DEBUG && echo "${file} does not exist" 1>&2
		return
	fi
	source ${file}
}

selectProject () {
  if [ "$DEV_TAG" ]; then echo $DEV_TAG; exit; fi
	local PS3 tag
	PS3="Select project: "
	select tag in `$DEV_HOME/bin/lsdev`; do
		echo "$tag" 1>&2
		if [ -z "${tag}" ]; then
			exit 0
		elif [ "${tag}" ]; then
			echo "${tag}"
			break;
		fi
	done
}

include ${DEV_HOME}/etc/conf
include ${DEV_HOME}/etc/conf.$HOSTNAME

if [ -z "${DEV}" ]; then
	echo "DEV is not set" 1>&2
	exit 1
fi

DEV_TAG="${1:-`selectProject`}"

if [ -z "${DEV_TAG}" ]; then
	exit
fi

DEV_DIR="${DEV}/${DEV_TAG}"

if [ ! -d "${DEV_DIR}" ]; then
	read -t 10 -p "${DEV_DIR} does not exist, create new project? (y/N)" new_project
	case "$new_project" in
	y*|Y*)
		mkdir -p "${DEV_DIR}"
		mkdir -p "${DEV_DIR}/.dev"
		;;
	*)
		PS3="Select existing project: "
		select tag in `$DEV_HOME/bin/lsdev`; do
			echo "'$tag'"
			if [ -z "${tag}" ]; then
				exit 0
			elif [ "${tag}" ]; then
				DEV_DIR="${DEV}/${tag}"
				break;
			fi
		done
		;;
	esac
fi

CMD=${2}
case "${CMD}" in
	conf)
		
	;;
	*)
	;;
esac

#
# Begin with the real task of this script:
#
# Set up the work environment
#

cd ${DEV_DIR}

include ${DEV_DIR}/${_DEV_CONF}

if [ -r "${DEV_DIR}/${_DEV_TOOLS}" ]; then
        echo -n "Using"
	for tool in `grep -v '^#' ${DEV_DIR}/${_DEV_TOOLS}`; do
                echo -n " $tool"
		include ${_DEV_TOOLS_DIR}/${tool}
		DEV_TOOL_SHARE=$DEV_HOME/lib/${DEV_TOOL:-$tool}
		if [ -d "$DEV_TOOL_SHARE" ]; then
			PATH="$DEV_TOOL_SHARE:$PATH"
		fi
		unset DEV_TOOL
	done
        echo ""
fi

if [ -d "$DEV_DIR/bin" ]; then
	PATH="$DEV_DIR/bin:$PATH"
fi

$DEV_TRACE && set +x

export PS1='\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]\n\$ '
export DEV_HOME DEV DEV_DIR DEV_TAG

exec ${SHELL}
